package com.work.demo.threaddemo;

/**
 * @ClassName : Jmm05
 * @Description : 使用jvm的Unsafe实现内存屏障,源码四期并发编程专题第二节1:23:00处
 * @Author : LinYa
 * @Date: 2022/1/20  15:59
 */
public class Jmm05 {

	private static int x = 0, y = 0;
	private static int a = 0, b = 0;


	public static void main(String[] args) throws InterruptedException {

		int i = 0;
		for (; ; ) {
			i++;
			x = 0;
			y = 0;
			a = 0;
			b = 0;
			Thread t1 = new Thread(new Runnable() {
				@Override
				public void run() {
					shortWait(10000);
					a = 1;
					UnsafeInstance.reflectGetUnsafe().fullFence();
					x = b;
				}
			});

			Thread t2 = new Thread(new Runnable() {
				@Override
				public void run() {
					b = 1;
					UnsafeInstance.reflectGetUnsafe().fullFence();
					y = a;
				}
			});

			t1.start();
			t2.start();
			t1.join();
			t2.join();

			System.out.println("第" + i + "次（" + x + "," + y + ")");
			if (x == 0 && y == 0) {
				System.out.println("第" + i + "次（" + x + "," + y + "),发生了指令重排,导致结果错误");
				break;
			}
		}

	}

	public static void shortWait(long interval) {
		long start = System.nanoTime();
		long end;
		do {
			end = System.nanoTime();
		} while (start + interval >= end);
	}
}
